/*
 * APICloud JavaScript Library
 * Copyright (c) 2014 apicloud.com
 */
//请求地址
var dataUrl = '';
// 页面适配
document.addEventListener('DOMContentLoaded', function () {
    var html = document.documentElement;
    var windowWidth = html.clientWidth;
    if (windowWidth > 750) {
        windowWidth = 750
    }
    html.style.fontSize = windowWidth / 7.5 + 'px';
}, false);
// 粘贴板内容监听
function resume(name) {
    var clipBoard = api.require("clipBoard");
    clipBoard.get(function (ret, err) {
        if (ret) {
            if (ret.value.length >= 2) {
                search(ret.value, name);
            }
        } else {
        }
    });
    // 监听应用进入后台事件
    api.addEventListener({
        name: 'pause'
    }, function (ret, err) {
        // if (api.frames().findIndex(item => {return item.name == "think_find"}) != -1 || api.frames().findIndex(item => {return item.name == "searchGoods_frm"}) != -1) {
        //     api.setFrameAttr({
        //         name: 'think_find',
        //         bgColor: "rgba(0,0,0,0)"
        //     });
        //     api.closeFrame({
        //         name: "think_find"
        //     });
        //     api.closeFrame({
        //         name: "searchGoods_frm"
        //     });
        // }
    });
    // 监听应用从后台返回前台
    api.addEventListener({
        name: 'resume'
    }, function (ret, err) {
        clipBoard.get(function (ret, err) {
            if (ret) {
                if (ret.value.length >= 2) {

                    search(ret.value, name);
                }
            } else {

                // alert(JSON.stringify(err));;
            }
        });
    });
}
// 对粘贴板复制的内容执行搜索
function search(clip, name) {
    // 正则验证
    var taokoulingstatus = false , lianjiestatue = false;
    var regex1 = new RegExp("^[\u4e00-\u9fa5]+$");
    if(regex1.test(clip)){
        return //纯文字
    }
    if(/^[0-9]*$/.test(clip)){
        return //纯数字
    }
    if(clip.indexOf("-") != -1 ){
        var pddClip = clip.replace("-","");
        if(/^[0-9]*$/.test(pddClip)){
            return //拼多多订单验证
        }
    }
    var regex2 = /(((https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/ig;
    if(regex2.test(clip)){  //校验正则文本内含有链接
        lianjiestatue = true;
        clip.replace(/&/g,"%26")
    }
    var regex3 = new RegExp("[A-Za-z0-9_]{8,14}");
    if(regex3.test(clip)){  //校验正则文本内含有淘口令
        taokoulingstatus = true;
    }
    if(lianjiestatue || taokoulingstatus){  //含有淘口令或者链接时执行搜索
        $api.ajax({
            url: 'api/goods/search',
            method: 'get',
            data: {
                values: {
                    q: clip,
                    source : 1
                }
            }
        }, function (ret) {
            if(ret.code==0){
                if (ret.data.list.length != 0 ) {
                    // 搜索后清空剪贴板内的数据
                    var clipBoard = api.require("clipBoard");
                    clipBoard.set({value:''}, function (ret, err){});
                    //解决 不同页面重复弹出
                    let windows = api.windows();
                    //判断最上层页面是否是 商品详情页
                    if (api.windows()[api.windows().length - 1].name != "root") {
                        api.closeToWin({name: 'root'});
                        //判断是都是商品详情页下的那个win  //猜你想找
                        think_find(ret.data, clip)
                    }
                    //判断是否是当前最顶层的win
                    if (api.windows()[api.windows().length - 1].name == 'root') {
                        think_find(ret.data, clip)
                    }
                }
            }else if (ret.code == 1) {
                api.toast({
                    msg: '此商品暂无优惠试试其他商品吧~',
                    duration: 1500,
                    location: 'middle'
                })
            }
        });
    }
}

//跳转搜索展示页面
function think_find(data, clip) {
    if(data.type == 1){ //链接单个商品展示页面
        api.openFrame({
            name: 'searchGoods_frm',
            url: 'widget://html/searchGoods_frm.html',
            bgColor: "rgba(0,0,0,0.2)",
            pageParam: {
                data: data.list[0]
            },
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            },
            animation: {
                type: "movein",
                subType: "from_bottom",
                duration: 300
            }
        });
    }else{ //跳转多个商品页面
        api.openFrame({
            name: 'think_find',
            url: 'widget://html/think_find.html',
            bgColor: "rgba(0,0,0,0.2)",
            pageParam: {
                data: data,
            },
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            },
            animation: {
                type: "movein",
                subType: "from_bottom",
                duration: 300
            }
        });
    }

}

function jump(url) {
    let aliBC = api.require('aliBC');
    if (url == "zero") {
        api.openTabLayout({
            name: 'zero',
            url: "widget://html/zero.html",
            useWKWebView: true,
            bgColor: '#fff',
        });
        return;
    }
    if (url.indexOf("https") != -1 || url.indexOf("http") != -1) {
        if (url.indexOf("taobao.com") != -1 || url.indexOf("tmall.com") != -1) {
            aliBC.showPageByUrl({
                url: url,
                backUrl: api.systemType != "android" ? "" : "tbopen24627965"
            }, function (ret, err) { });
            return;
        }
        api.openTabLayout({
            name: 'url',
            url: "widget://html/Url.html",
            useWKWebView: true,
            bgColor: '#fff',
            pageParam: {
                url: url,
            }
        });
        return;
    }
    api.openTabLayout({
        name: 'Result',
        url: 'widget://html/home/search_result.html',
        useWKWebView: true,
        bgColor: '#fff',
        pageParam: {
            string: url,
        }
    });
}
//佣金
function Rebate(x) {
    var config_info = api.getGlobalData({
        key: 'config_info'
    })
    var a;
    eval(config_info.formula);
    return a
}

//是否登录
function getToken() {
    if ($api.getStorage('token')) {
        return true;
    }
    api.openTabLayout({
        name: 'login_win',
        url: 'widget://html/login/login_win.html',
        useWKWebView: true,
        bgColor: '#fff',
    });
}

//图片加载失败
function showDefaultImg(img) {
    img.src = "widget://image/img_failedtoload.png";
    img.onerror = null;
}

//请求超时
function timeout(e) {
    e.innerHTML = `
  <div class="timeout">
        <div>请求失败</div>
        <div>请检查网络后重试</div>
        <div onclick="reload()">重新加载</div>
    </div>
    `;
}

//刷新
function reload() {
    window.location.reload();
}

function getLocalTime(nS) {
    now = new Date(nS * 1000)
    var year = now.getFullYear();  //取得4位数的年份
    var month = formatNumber(now.getMonth() + 1);  //取得日期中的月份，其中0表示1月，11表示12月
    var date = formatNumber(now.getDate());      //返回日期月份中的天数（1到31）
    var hour = formatNumber(now.getHours());     //返回日期中的小时数（0到23）
    var minute = formatNumber(now.getMinutes()); //返回日期中的分钟数（0到59）
    var second = formatNumber(now.getSeconds()); //返回日期中的秒数（0到59）
    return year + "-" + month + "-" + date + " " + hour + ":" + minute;
}

function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}

(function (window) {
    var u = {};
    var isAndroid = (/android/gi).test(navigator.appVersion);
    var uzStorage = function () {
        var ls = window.localStorage;
        if (isAndroid) {
            ls = os.localStorage();
        }
        return ls;
    };

    function parseArguments(url, data, fnSuc, dataType) {
        if (typeof (data) == 'function') {
            dataType = fnSuc;
            fnSuc = data;
            data = undefined;
        }
        if (typeof (fnSuc) != 'function') {
            dataType = fnSuc;
            fnSuc = undefined;
        }
        return {
            url: url,
            data: data,
            fnSuc: fnSuc,
            dataType: dataType
        };
    }

    dataUrl = u.baseUrl
    u.ajax = function (json) {
        api.addEventListener({
            name: 'online'
        }, function (ret, err) {
            api.toast({
                msg: '已连接到网络',
                duration: 3000,
                location: 'middle'
            })
            reload()
        });
        var argsToJson = parseArguments.apply(null, arguments);
        var fnSuc = argsToJson.fnSuc;
        api.ajax(json,function (ret, err) {
            if (ret) {
                fnSuc && fnSuc(ret);
            } else {
                if (err.statusCode == 401) {
                    //token过期
                    api.toast({
                        msg: "登录过期，请重新登录",
                        duration: 3000,
                        location: 'middle'
                    })
                    u.setStorage('token', '')
                    api.openTabLayout({
                        name: 'login_win',
                        url: 'widget://html/login/login_win.html',
                        useWKWebView: true,
                        bgColor: '#fff',
                    });
                } else {
                    if (json.url != u.baseUrl + "api/goods/search") {
                        api.toast({
                            msg: err.body.msg,
                            duration: 3000,
                            location: 'middle'
                        })
                    }
                    if (err.statusCode == 0) {
                        api.toast({
                            msg: "请求失败，请检查网络后重试",
                            duration: 3000,
                            location: 'middle'
                        });
                        if (json.timeOutHtml) {
                            timeout(json.timeOutHtml)
                        }
                    } else {
                        if (err.body) {
                            // fnSuc && fnSuc(err);// console.log(json.url)
                        } else {
                        }
                    }
                }
            }
        });
    }

    u.trim = function (str) {
        if (String.prototype.trim) {
            return str == null ? "" : String.prototype.trim.call(str);
        } else {
            return str.replace(/(^\s*)|(\s*$)/g, "");
        }
    };
    u.trimAll = function (str) {
        return str.replace(/\s*/g, '');
    };
    u.isElement = function (obj) {
        return !!(obj && obj.nodeType == 1);
    };
    u.isArray = function (obj) {
        if (Array.isArray) {
            return Array.isArray(obj);
        } else {
            return obj instanceof Array;
        }
    };
    u.isEmptyObject = function (obj) {
        if (JSON.stringify(obj) === '{}') {
            return true;
        }
        return false;
    };
    u.addEvt = function (el, name, fn, useCapture) {
        if (!u.isElement(el)) {
            console.warn('$api.addEvt Function need el param, el param must be DOM Element');
            return;
        }
        useCapture = useCapture || false;
        if (el.addEventListener) {
            el.addEventListener(name, fn, useCapture);
        }
    };
    u.rmEvt = function (el, name, fn, useCapture) {
        if (!u.isElement(el)) {
            console.warn('$api.rmEvt Function need el param, el param must be DOM Element');
            return;
        }
        useCapture = useCapture || false;
        if (el.removeEventListener) {
            el.removeEventListener(name, fn, useCapture);
        }
    };
    u.one = function (el, name, fn, useCapture) {
        if (!u.isElement(el)) {
            console.warn('$api.one Function need el param, el param must be DOM Element');
            return;
        }
        useCapture = useCapture || false;
        var that = this;
        var cb = function () {
            fn && fn();
            that.rmEvt(el, name, cb, useCapture);
        };
        that.addEvt(el, name, cb, useCapture);
    };
    u.dom = function (el, selector) {
        if (arguments.length === 1 && typeof arguments[0] == 'string') {
            if (document.querySelector) {
                return document.querySelector(arguments[0]);
            }
        } else if (arguments.length === 2) {
            if (el.querySelector) {
                return el.querySelector(selector);
            }
        }
    };
    u.domAll = function (el, selector) {
        if (arguments.length === 1 && typeof arguments[0] == 'string') {
            if (document.querySelectorAll) {
                return document.querySelectorAll(arguments[0]);
            }
        } else if (arguments.length === 2) {
            if (el.querySelectorAll) {
                return el.querySelectorAll(selector);
            }
        }
    };
    u.byId = function (id) {
        return document.getElementById(id);
    };
    u.first = function (el, selector) {
        if (arguments.length === 1) {
            if (!u.isElement(el)) {
                console.warn('$api.first Function need el param, el param must be DOM Element');
                return;
            }
            return el.children[0];
        }
        if (arguments.length === 2) {
            return this.dom(el, selector + ':first-child');
        }
    };
    u.last = function (el, selector) {
        if (arguments.length === 1) {
            if (!u.isElement(el)) {
                console.warn('$api.last Function need el param, el param must be DOM Element');
                return;
            }
            var children = el.children;
            return children[children.length - 1];
        }
        if (arguments.length === 2) {
            return this.dom(el, selector + ':last-child');
        }
    };
    u.eq = function (el, index) {
        return this.dom(el, ':nth-child(' + index + ')');
    };
    u.not = function (el, selector) {
        return this.domAll(el, ':not(' + selector + ')');
    };
    u.prev = function (el) {
        if (!u.isElement(el)) {
            console.warn('$api.prev Function need el param, el param must be DOM Element');
            return;
        }
        var node = el.previousSibling;
        if (node.nodeType && node.nodeType === 3) {
            node = node.previousSibling;
            return node;
        }
    };
    u.next = function (el) {
        if (!u.isElement(el)) {
            console.warn('$api.next Function need el param, el param must be DOM Element');
            return;
        }
        var node = el.nextSibling;
        if (node.nodeType && node.nodeType === 3) {
            node = node.nextSibling;
            return node;
        }
    };
    u.closest = function (el, selector) {
        if (!u.isElement(el)) {
            console.warn('$api.closest Function need el param, el param must be DOM Element');
            return;
        }
        var doms, targetDom;
        var isSame = function (doms, el) {
            var i = 0, len = doms.length;
            for (i; i < len; i++) {
                if (doms[i].isSameNode(el)) {
                    return doms[i];
                }
            }
            return false;
        };
        var traversal = function (el, selector) {
            doms = u.domAll(el.parentNode, selector);
            targetDom = isSame(doms, el);
            while (!targetDom) {
                el = el.parentNode;
                if (el != null && el.nodeType == el.DOCUMENT_NODE) {
                    return false;
                }
                traversal(el, selector);
            }

            return targetDom;
        };

        return traversal(el, selector);
    };
    u.contains = function (parent, el) {
        var mark = false;
        if (el === parent) {
            mark = true;
            return mark;
        } else {
            do {
                el = el.parentNode;
                if (el === parent) {
                    mark = true;
                    return mark;
                }
            } while (el === document.body || el === document.documentElement);

            return mark;
        }

    };
    u.remove = function (el) {
        if (el && el.parentNode) {
            el.parentNode.removeChild(el);
        }
    };
    u.attr = function (el, name, value) {
        if (!u.isElement(el)) {
            console.warn('$api.attr Function need el param, el param must be DOM Element');
            return;
        }
        if (arguments.length == 2) {
            return el.getAttribute(name);
        } else if (arguments.length == 3) {
            el.setAttribute(name, value);
            return el;
        }
    };
    u.removeAttr = function (el, name) {
        if (!u.isElement(el)) {
            console.warn('$api.removeAttr Function need el param, el param must be DOM Element');
            return;
        }
        if (arguments.length === 2) {
            el.removeAttribute(name);
        }
    };
    u.hasCls = function (el, cls) {
        if (!u.isElement(el)) {
            console.warn('$api.hasCls Function need el param, el param must be DOM Element');
            return;
        }
        if (el.className.indexOf(cls) > -1) {
            return true;
        } else {
            return false;
        }
    };
    u.addCls = function (el, cls) {
        if (!u.isElement(el)) {
            console.warn('$api.addCls Function need el param, el param must be DOM Element');
            return;
        }
        if ('classList' in el) {
            el.classList.add(cls);
        } else {
            var preCls = el.className;
            var newCls = preCls + ' ' + cls;
            el.className = newCls;
        }
        return el;
    };
    u.removeCls = function (el, cls) {
        if (!u.isElement(el)) {
            console.warn('$api.removeCls Function need el param, el param must be DOM Element');
            return;
        }
        if ('classList' in el) {
            el.classList.remove(cls);
        } else {
            var preCls = el.className;
            var newCls = preCls.replace(cls, '');
            el.className = newCls;
        }
        return el;
    };
    u.toggleCls = function (el, cls) {
        if (!u.isElement(el)) {
            console.warn('$api.toggleCls Function need el param, el param must be DOM Element');
            return;
        }
        if ('classList' in el) {
            el.classList.toggle(cls);
        } else {
            if (u.hasCls(el, cls)) {
                u.removeCls(el, cls);
            } else {
                u.addCls(el, cls);
            }
        }
        return el;
    };
    u.val = function (el, val) {
        if (!u.isElement(el)) {
            console.warn('$api.val Function need el param, el param must be DOM Element');
            return;
        }
        if (arguments.length === 1) {
            switch (el.tagName) {
                case 'SELECT':
                    var value = el.options[el.selectedIndex].value;
                    return value;
                    break;
                case 'INPUT':
                    return el.value;
                    break;
                case 'TEXTAREA':
                    return el.value;
                    break;
            }
        }
        if (arguments.length === 2) {
            switch (el.tagName) {
                case 'SELECT':
                    el.options[el.selectedIndex].value = val;
                    return el;
                    break;
                case 'INPUT':
                    el.value = val;
                    return el;
                    break;
                case 'TEXTAREA':
                    el.value = val;
                    return el;
                    break;
            }
        }

    };
    u.prepend = function (el, html) {
        if (!u.isElement(el)) {
            console.warn('$api.prepend Function need el param, el param must be DOM Element');
            return;
        }
        el.insertAdjacentHTML('afterbegin', html);
        return el;
    };
    u.append = function (el, html) {
        if (!u.isElement(el)) {
            console.warn('$api.append Function need el param, el param must be DOM Element');
            return;
        }
        el.insertAdjacentHTML('beforeend', html);
        return el;
    };
    u.before = function (el, html) {
        if (!u.isElement(el)) {
            console.warn('$api.before Function need el param, el param must be DOM Element');
            return;
        }
        el.insertAdjacentHTML('beforebegin', html);
        return el;
    };
    u.after = function (el, html) {
        if (!u.isElement(el)) {
            console.warn('$api.after Function need el param, el param must be DOM Element');
            return;
        }
        el.insertAdjacentHTML('afterend', html);
        return el;
    };
    u.html = function (el, html) {
        if (!u.isElement(el)) {
            console.warn('$api.html Function need el param, el param must be DOM Element');
            return;
        }
        if (arguments.length === 1) {
            return el.innerHTML;
        } else if (arguments.length === 2) {
            el.innerHTML = html;
            return el;
        }
    };
    u.text = function (el, txt) {
        if (!u.isElement(el)) {
            console.warn('$api.text Function need el param, el param must be DOM Element');
            return;
        }
        if (arguments.length === 1) {
            return el.textContent;
        } else if (arguments.length === 2) {
            el.textContent = txt;
            return el;
        }
    };
    u.offset = function (el) {
        if (!u.isElement(el)) {
            console.warn('$api.offset Function need el param, el param must be DOM Element');
            return;
        }
        var sl = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
        var st = Math.max(document.documentElement.scrollTop, document.body.scrollTop);

        var rect = el.getBoundingClientRect();
        return {
            l: rect.left + sl,
            t: rect.top + st,
            w: el.offsetWidth,
            h: el.offsetHeight
        };
    };
    u.css = function (el, css) {
        if (!u.isElement(el)) {
            console.warn('$api.css Function need el param, el param must be DOM Element');
            return;
        }
        if (typeof css == 'string' && css.indexOf(':') > 0) {
            el.style && (el.style.cssText += ';' + css);
        }
    };
    u.cssVal = function (el, prop) {
        if (!u.isElement(el)) {
            console.warn('$api.cssVal Function need el param, el param must be DOM Element');
            return;
        }
        if (arguments.length === 2) {
            var computedStyle = window.getComputedStyle(el, null);
            return computedStyle.getPropertyValue(prop);
        }
    };
    u.jsonToStr = function (json) {
        if (typeof json === 'object') {
            return JSON && JSON.stringify(json);
        }
    };
    u.strToJson = function (str) {
        if (typeof str === 'string') {
            return JSON && JSON.parse(str);
        }
    };
    u.setStorage = function (key, value) {
        if (arguments.length === 2) {
            var v = value;
            if (typeof v == 'object') {
                v = JSON.stringify(v);
                v = 'obj-' + v;
            } else {
                v = 'str-' + v;
            }
            var ls = uzStorage();
            if (ls) {
                ls.setItem(key, v);
            }
        }
    };
    u.getStorage = function (key) {
        var ls = uzStorage();
        if (ls) {
            var v = ls.getItem(key);
            if (!v) { return; }
            if (v.indexOf('obj-') === 0) {
                v = v.slice(4);
                return JSON.parse(v);
            } else if (v.indexOf('str-') === 0) {
                return v.slice(4);
            }
        }
    };
    u.rmStorage = function (key) {
        var ls = uzStorage();
        if (ls && key) {
            ls.removeItem(key);
        }
    };
    u.clearStorage = function () {
        var ls = uzStorage();
        if (ls) {
            ls.clear();
        }
    };
    u.fixIos7Bar = function (el) {
        return u.fixStatusBar(el);
    };
    u.fixStatusBar = function (el) {
        if (!u.isElement(el)) {
            console.warn('$api.fixStatusBar Function need el param, el param must be DOM Element');
            return 0;
        }
        el.style.paddingTop = api.safeArea.top + 'px';
        return el.offsetHeight;
    };
    u.fixTabBar = function (el) {
        if (!u.isElement(el)) {
            console.warn('$api.fixTabBar Function need el param, el param must be DOM Element');
            return 0;
        }
        el.style.paddingBottom = api.safeArea.bottom + 'px';
        return el.offsetHeight;
    };
    u.toast = function (title, text, time) {
        var opts = {};
        var show = function (opts, time) {
            api.showProgress(opts);
            setTimeout(function () {
                api.hideProgress();
            }, time);
        };
        if (arguments.length === 1) {
            var time = time || 500;
            if (typeof title === 'number') {
                time = title;
            } else {
                opts.title = title + '';
            }
            show(opts, time);
        } else if (arguments.length === 2) {
            var time = time || 500;
            var text = text;
            if (typeof text === "number") {
                var tmp = text;
                time = tmp;
                text = null;
            }
            if (title) {
                opts.title = title;
            }
            if (text) {
                opts.text = text;
            }
            show(opts, time);
        }
        if (title) {
            opts.title = title;
        }
        if (text) {
            opts.text = text;
        }
        time = time || 500;
        show(opts, time);
    };
    u.post = function (/*url,data,fnSuc,dataType*/) {
        var argsToJson = parseArguments.apply(null, arguments);
        var json = {};
        var fnSuc = argsToJson.fnSuc;
        argsToJson.url && (json.url = argsToJson.url);
        argsToJson.data && (json.data = argsToJson.data);
        if (argsToJson.dataType) {
            var type = argsToJson.dataType.toLowerCase();
            if (type == 'text' || type == 'json') {
                json.dataType = type;
            }
        } else {
            json.dataType = 'json';
        }
        json.method = 'post';
        api.ajax(json,
            function (ret, err) {
                if (ret) {
                    fnSuc && fnSuc(ret);
                }
            }
        );
    };
    u.get = function (/*url,fnSuc,dataType*/) {
        var argsToJson = parseArguments.apply(null, arguments);
        var json = {};
        var fnSuc = argsToJson.fnSuc;
        argsToJson.url && (json.url = argsToJson.url);
        //argsToJson.data && (json.data = argsToJson.data);
        if (argsToJson.dataType) {
            var type = argsToJson.dataType.toLowerCase();
            if (type == 'text' || type == 'json') {
                json.dataType = type;
            }
        } else {
            json.dataType = 'text';
        }
        json.method = 'get';
        api.ajax(json,
            function (ret, err) {
                if (ret) {
                    fnSuc && fnSuc(ret);
                }
            }
        );
    };
    /*end*/

    window.$api = u;

})(window);
